import { AuthTokenType, UserAction } from '@/store/reducer/user';
import { AppDispatch } from '@/store';
import { LoginApi, SendCodeApi } from '@/api/login';
import { SetToken } from '@/utils/storage';

export type FormDataType = {
  mobile: string;
  code: string;
};

/** 发送验证码Acion */
export function SendCodeAction(mobile: string) {
  return async () => {
    await SendCodeApi(mobile);
  };
}

/** 登录Acion */
export function LoginAction(formdata: FormDataType) {
  return async (dispatch: AppDispatch) => {
    const res = await LoginApi(formdata);
    SetToken(res.data);
    dispatch({ type: 'user/SaveAuthToken', payload: res.data });
  };
}

/** 更新并储存Token Acion */
export function UpdateTokenAction(data: AuthTokenType): UserAction {
  SetToken(data);
  return { type: 'user/SaveAuthToken', payload: data };
}
